<?php

namespace App\Controller\AppCommon;

use App\Base\BaseCache;
use App\Base\BaseController4Restful;
use App\Base\Format;
use App\BaseExt\SmsTencent;
use App\Entity\Shop;
use App\Entity\User;
use App\Repository\ChatRepository;
use App\Repository\ConfigRepository;
use App\Repository\UserLevelRepository;
use App\Repository\UserRepository;
use App\Service\MoneyService;
use App\BaseExt\Captcha;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;

/**
 * @route("/app")
 */
class AppUserController extends BaseController4Restful
{

    /**
     * @Route("/send_sms",name="AppSendSms")
     */
    public function AppSendSms()
    {
        if (!$phone = $this->getParamRequired("phone")) {return $this->json_out(400,"请输入手机号");}
        $is = new Format();
        if (!$is->isPhone($phone)) {
            return $this->json_out(400,"手机号错误");
        }

        $lastTime = $this->getUserCache("smsLastTime");
        if ($lastTime > time() - 18) {
            return $this->json_out(400,"操作太频繁");
        }
        $smsRecentCount = $this->getUserCache("smsRecentCount");
        $smsRecentDate = $this->getUserCache("smsRecentDate");
        if (!$smsRecentCount || $smsRecentDate != date("Ymd") ) {
            $smsRecentCount = 1;
        }else{
            $smsRecentCount++;
        }
        if ($smsRecentCount > 50) {
            return $this->json_out(400,"尝试次数超出上限");
        }

//        require_once __DIR__."/../../../BaseExt/Sms.php";
//        $sms = new \Sms();
        $rand = rand(1000,9999);
//        $sms->sendSms($phone,"SMS_174166578",array("code"=>$rand));
        $this->setUserCache("smsCode",$rand);
        $this->setUserCache("smsLastTime",time());
        $this->setUserCache("smsLastPhone",$phone);
        $this->setUserCache("smsRecentCount",$smsRecentCount);
        $this->setUserCache("smsRecentDate",date("Ymd"));

//        return $this->json_out(200,"已发送 $rand","$rand");
        $sms = new SmsTencent();
        $sms->sendSms($phone,"566899",$rand);

        return $this->json_out(200,"已发送","$rand");
    }


    /**
     * @Route("/login_sms",name="AppUserSMSLogin")
     */
    public function AppUserSMSLogin(Request $request , UserRepository $userRepository)
    {
        if (!$phone = $this->getParamRequired("phone")) {return $this->json_out(400,"请输入手机号");}
        $is = new Format();
        if (!$is->isPhone($phone)) {return $this->json_out(400,"手机号错误");}
        $smsLastPhone = $this->getUserCache("smsLastPhone");
        if ($smsLastPhone != $phone) {return $this->json_out(400,"手机号不一致");}
        $smsCode = $this->getUserCache("smsCode");
        if (!$code = $this->getParamRequired("code")) {return $this->json_out(400,"请输入验证码");}
        if ($code != $smsCode) {return $this->json_out(400,"验证码错误");}
        $user = $userRepository->findOneBy(array("phone"=>$phone));
        if (!$user) {
            $user = new User();
            $user->setApiToken($phone)
                ->setPhone($phone)->setAvatar("/ApiCloud/assets/img/userHead.jpeg")->setPassword(md5($phone))
                ->setCreateAt(new \DateTime())
                ->setName("用户" . rand(1000,9999));
        }
        $this->myEm()->persist($user);
        $this->myEm()->flush();
        //设置缓存
        $sessionData = array(
            "id" => $user->getId()
        ,"name"=>$user->getName()
        ,"phone"=>$user->getPhone()
        ,"avatar"=>$user->getAvatar()
        ,"apiToken"=>$user->getPhone()
        );
        //启用Cache
        $this->setUserCache('user',$sessionData);

        $this->setGroups("user");
        return $this->json_out(200,"注册成功",$user);
//        return $this->json_out(200,"登录成功",$sessionData);
    }

    /**
     * @Route("/reg_sms_password",name="AppUserSMSPasswordReg")
     */
    public function AppUserSMSPasswordReg(
        Request $request
        , UserRepository $userRepository
        , MoneyService $moneyService
        ,ConfigRepository $configRepository
        ,UserLevelRepository $userLevelRepository
        ,ChatRepository $chatRepository
    )
    {
        if (!$phone = $this->getParamRequired("phone")) {return $this->json_out(400,"请输入手机号");}
        if (!$password = $this->getParamRequired("password")){return $this->json_out(400,"请输入密码");}
        if (!$code = $this->getParamRequired("code")) {return $this->json_out(400,"请输入验证码");}
        $is = new Format();
        if (!$is->isPhone($phone)) {return $this->json_out(400,"手机号错误");}
        $smsLastPhone = $this->getUserCache("smsLastPhone");
        if ($smsLastPhone != $phone) {return $this->json_out(400,"手机号不一致");}
        $smsCode = $this->getUserCache("smsCode");
        if (strtolower($code) != strtolower($smsCode)) {return $this->json_out(400,"验证码错误");}
        $user = $userRepository->findOneBy(array("phone"=>$phone));
        if ($user) {
            return $this->json_out(400,"手机号已占用");
        }else{
            $user = new User();
            $user->setApiToken($phone)
                ->setPhone($phone)->setAvatar("/ApiCloud/assets/img/userHead.jpeg")->setPassword(md5($password))
                ->setCreateAt(new \DateTime())
                ->setLevel($userLevelRepository->findMin())
                ->setExpr(0)
                ->setSex(1)
                ->setName("用户" . rand(1000,9999));
        }
        $this->myEm()->persist($user);
        $this->myEm()->flush();
        //设置缓存
        $sessionData = array(
            "id" => $user->getId()
        ,"name"=>$user->getName()
        ,"phone"=>$user->getPhone()
        ,"avatar"=>$user->getAvatar()
        ,"apiToken"=>$user->getPhone()
        );
        //启用Cache
        $this->setUserCache('user',$sessionData);

        //注册奖励
        $regBonus = (int)$configRepository->getByK("REG_BONUS");
        //实际的积分记录
        $moneyService->mod($user,$regBonus,MoneyService::__MONEY_JI_FEN__,160,"注册奖励");


        //推广返利
        if(!$parent = $this->getParamRequired("parent")){$parent = "";}
        if ($parent){
            $parentUser = $userRepository->find($parent);
            if (!$parentUser) {
                $parentUser = $userRepository->findOneByPhone($parent);
            }
            if ($parentUser) {
                $user->setParent($parentUser);
                $this->myEm()->persist($user);
                $this->myEm()->flush();
                $inviteBonus = $configRepository->getByK("INVITE_BONUS");
                $inviteArray = myExplodeNumbers($inviteBonus);
                if (!is_array($inviteArray)) {
                    $inviteArray = [];
                }
                foreach ($inviteArray as $bonus) {
                    if (!$parentUser) {
                        continue;
                    }
                    $inviteBonus = $bonus;
                    //实际的积分记录
                    $moneyService->mod($parentUser,$inviteBonus,MoneyService::__MONEY_JI_FEN__,161,"邀请奖励");
                    //做数据统计用的记录，不用做列表展示
                    $moneyService->mod($parentUser,$inviteBonus,MoneyService::__MONEY_INVITE__,110,"邀请奖励积分记录");
                    //增加用户经验值
                    $parentUser->addExpr($inviteBonus);
                    $userRepository->dealWithLevel($parentUser);
                    $parentUser = $parentUser->getParent();
                }

            }
        }
        //欢迎注册
        $chatRepository->chatSingleReply(0,$user,$configRepository->getByK("CHAT_REG"),1);

        $this->setGroups("user");
        return $this->json_out(200,"注册成功",$user);
//        return $this->json_out(200,"注册成功",$sessionData);
    }


    /**
     * @route("/imgCode",name="getCaptchaJsonimgCode")
     */
    public function getCaptchaJsonimgCode(Request $request)
    {
        $captcha = new Captcha($request);
        $data = $captcha->dobase64();
        $code = $captcha->getCode();
        $this->setUserCache("CaptchaCode",$code);
        return $this->json_out(200,"OK",$data);
    }


    /**
     * @Route("/login_sms_password",name="AppUserSMSAndPasswordLogin")
     */
    public function AppUserSMSAndPasswordLogin(Request $request , UserRepository $userRepository,ChatRepository $chatRepository,ConfigRepository $configRepository)
    {
        if (!$phone = $this->getParamRequired("phone")) {return $this->json_out(400,"请输入手机号");}
        if(!$password = $this->getParamRequired("password")){return $this->json_out(400,"请输入密码");}
        $is = new Format();
        if (!$is->isPhone($phone)) {return $this->json_out(400,"手机号错误");}

        //验证码相关
//        if (!$code = $this->getParamRequired("code")) {return $this->json_out(400,"请输入验证码");}
//        $smsLastPhone = $this->getUserCache("smsLastPhone");
//        if ($smsLastPhone != $phone) {return $this->json_out(400,"手机号不一致");}
//        $smsCode = $this->getUserCache("smsCode");
//        if ($code != $smsCode) {return $this->json_out(400,"验证码错误");}

        if (!$code = $this->getParamRequired("code")) {return $this->json_out(400,"请输入验证码");}
        $smsCode = $this->getUserCache("CaptchaCode");
        if ( strtolower($code) != strtolower($smsCode) ) {return $this->json_out(400,"验证码错误");}


        $user = $userRepository->findOneBy(array("phone"=>$phone));
        if (!$user) {
            return $this->json_out(400,"手机号或密码错误");
        }
        if ($user->getPassword() != md5($password)) {
            return $this->json_out(400,"手机号或密码错误");
        }
        if ($user->getStatus() == 1) {
            return $this->json_out(400,"禁止登陆");
        }

        //todo 每次登陆应该更新一下apiToken,以确保登陆设备的唯一性

        $this->myEm()->persist($user);
        $this->myEm()->flush();
        //设置缓存
        $sessionData = array(
            "id" => $user->getId()
            ,"name"=>$user->getName()
            ,"phone"=>$user->getPhone()
            ,"avatar"=>$user->getAvatar()
            ,"apiToken"=>$user->getPhone()
        );
        $this->mySession()->set("user",$sessionData);
        //启用Cache
        $this->setUserCache('user',$sessionData);


        //欢迎注册
        $chatRepository->chatSingleReply(0,$user,$configRepository->getByK("CHAT_LOGIN"),1);

        $this->setGroups("user","home","task");
        return $this->json_out(200,"登录成功",$user);
    }



    /**
     * @Route("/delete_self",name="AppUserDeleteSelf")
     */
    public function AppUserDeleteSelf(Request $request , UserRepository $userRepository)
    {
        $user = $this->needToBeUser();
        $rnd = uniqid($user->getId());
        $user->setPassword($rnd)
            ->setApiToken($rnd)
        ;
        $this->myEm()->persist($user);
        $this->myEm()->flush();

        return $this->json_out(200,"滚犊子");
    }


    /**
     * @Route("/forget_password",name="AppUserForgetPassword")
     */
    public function AppUserForgetPassword(Request $request , UserRepository $userRepository)
    {
        if (!$phone = $this->getParamRequired("phone")) {return $this->json_out(400,"请输入手机号");}
        if (!$code = $this->getParamRequired("code")) {return $this->json_out(400,"请输入验证码");}
        if(!$password = $this->getParamRequired("password")){return $this->json_out(400,"请输入密码");}
        $is = new Format();
        if (!$is->isPhone($phone)) {return $this->json_out(400,"手机号错误");}
        $smsLastPhone = $this->getUserCache("smsLastPhone");
        if ($smsLastPhone != $phone) {return $this->json_out(400,"手机号不一致");}
        $smsCode = $this->getUserCache("smsCode");
        if ($code != $smsCode) {return $this->json_out(400,"验证码错误");}
        $user = $userRepository->findOneBy(array("phone"=>$phone));

        $user->setPassword(md5($password));

        //todo 每次登陆应该更新一下apiToken,以确保登陆设备的唯一性

        $this->myEm()->persist($user);
        $this->myEm()->flush();
        //设置缓存
        $sessionData = array(
            "id" => $user->getId()
        ,"name"=>$user->getName()
        ,"phone"=>$user->getPhone()
        ,"avatar"=>$user->getAvatar()
        ,"apiToken"=>$user->getPhone()
        );
        //启用Cache
        $this->setUserCache('user',$sessionData);

        return $this->json_out(200,"登录成功",$sessionData);
    }



    /**
     * @Route("/wechat_login",name="AppUserWeChatLogin")
     */
    public function AppUserWeChatLogin(
        Request $request
        , UserRepository $userRepository
        , ChatRepository $chatRepository
        , ConfigRepository $configRepository
    )
    {
        $req = $this->getRequestData();
        $openid = $req["openid"]??"";
        if (!$openid) {
            return $this->json_out(400,"登陆失败");
        }

        $user = $userRepository->findOneBy(array("openid"=>$openid));

        if (!$user) {
            return $this->json_out(400,"请先注册绑定微信后再使用微信登陆");
        }
        if ($user->getStatus() == 1) {
            return $this->json_out(400,"禁止登陆");
        }

        //todo 每次登陆应该更新一下apiToken,以确保登陆设备的唯一性

        $this->myEm()->persist($user);
        $this->myEm()->flush();
        //设置缓存
        $sessionData = array(
            "id" => $user->getId()
            ,"name"=>$user->getName()
            ,"phone"=>$user->getPhone()
            ,"avatar"=>$user->getAvatar()
            ,"apiToken"=>$user->getPhone()
        );
        $this->mySession()->set("user",$sessionData);
        //启用Cache
        $this->setUserCache('user',$sessionData);


        //欢迎注册
        $chatRepository->chatSingleReply(0,$user,$configRepository->getByK("CHAT_LOGIN"),1);

        $this->setGroups("user","home","task");
        return $this->json_out(200,"登录成功",$user);
    }

    /**
     * @Route("/wechat_bind",name="AppUserWeChatBind")
     */
    public function AppUserWeChatBind(
        UserRepository $userRepository
    )
    {
        $user = $this->needToBeUser();
        $req = $this->getRequestData();
        $openid = $req["openid"]??"";
        if (!$openid) {
            return $this->json_out(400,"登陆失败");
        }

        $find = $userRepository->findOneBy(array("openid"=>$openid));

        if ($find || $user->getOpenid()) {
            return $this->json_out(400,"该账号已绑定微信");
        }else{
            $user->setOpenid( $openid);
            $this->myEm()->persist($user);
            $this->myEm()->flush();
        }

        $this->setGroups("user","home","task");
        return $this->json_out(200,"登录成功",$user);
    }

}
